package demo.spring.restful.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.springframework.stereotype.Component;

import demo.spring.restful.domain.Computer;

@Component
public class ComputerService {
	private static final AtomicLong counter = new AtomicLong();

	private static List<Computer> computers;

	static {
		computers = populateDummyComputers();
	}

	public List<Computer> findAllComputers() {
		return computers;
	}

	public Computer findById(long id) {
		for (Computer computer : computers) {
			if (computer.getId() == id) {
				return computer;
			}
		}
		return null;
	}

	public Computer findByBrandAndVersion(String brand, String version) {
		for (Computer computer : computers) {
			if (computer.getBrand().equalsIgnoreCase(brand)
					&& computer.getVersion().equalsIgnoreCase(version)) {
				return computer;
			}
		}
		return null;
	}

	public void saveComputer(Computer computer) {
		computer.setId(counter.incrementAndGet());
		computers.add(computer);
	}

	public void updateComputer(Computer computer) {
		int index = computers.indexOf(computer);
		computers.set(index, computer);
	}

	public void deleteComputerById(long id) {

		for (Iterator<Computer> iterator = computers.iterator(); iterator
				.hasNext();) {
			Computer computer = iterator.next();
			if (computer.getId() == id) {
				iterator.remove();
			}
		}
	}

	public boolean isComputerExist(Computer computer) {
		return findByBrandAndVersion(computer.getBrand(), computer.getVersion()) != null;
	}

	private static List<Computer> populateDummyComputers() {
		List<Computer> computers = new ArrayList<Computer>();
		computers.add(new Computer(counter.incrementAndGet(), "联想小新700旗舰版",
				"Windows 10 Home", "8G", "15.6"));
		computers.add(new Computer(counter.incrementAndGet(),
				"戴尔Inspiron 灵越 15 7000系列", "Windows 10 Home Basic 64bit", "4G",
				"15.6"));
		computers.add(new Computer(counter.incrementAndGet(), "三星",
				"WIndows 8.1", "16G", "14"));
		computers.add(new Computer(counter.incrementAndGet(), "惠普",
				"Ubuntu 15.04", "8G", "15.6"));
		return computers;
	}

	public void deleteAllcomputers() {
		computers.clear();
	}
}


